/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.common.io;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sss.common.DataReceiver;
import org.sss.common.ErrorDataReceiverException;
import org.sss.common.KeyValues;
import org.sss.mapreduce.Configuration;
import org.sss.mapreduce.GroupID;
import org.sss.mapreduce.SssException;
import org.sss.mapreduce.StorageNode;

/**
 * .
 * NOTE: access int only this module.
 */
abstract class AbstractKeyValueReader extends AbstractDataReader {
  private static Logger logger = LoggerFactory.getLogger(AbstractKeyValueReader.class);

  protected final DataReceiver<List<KeyValues>> next;
  protected final int subhash;
  protected StorageNode node;

  public AbstractKeyValueReader(Configuration conf, StorageNode node,
    GroupID inputGID, int subhash, DataReceiver<List<KeyValues>> next) throws SssException {
    super(inputGID, conf);
    this.next    = next;
    this.subhash = subhash;
    this.node    = node;
  }

  @Override
  public void run() {
    try {
      doRead(IOThread.currentThread());
      next.close();
    }
    catch (InterruptedException e) {
      logger.error("Ignore InterruptedException", e);
    }
    catch (ErrorDataReceiverException e) {
      logger.debug("Ignore ErrorDataReceiverException", e);
    }
    catch (Throwable e) {
      logger.error("caught an Exception", e);
      next.setError(e);
    }
  }

  protected abstract void doRead(IOThread iot)
    throws SssException, IOException, InterruptedException;
}
